import { createStore } from 'vuex'
import { getInfoApi, loginApi, logoutApi } from '@/api/manager'
import { removeToken, setToken } from '@/utils/auth'

// 创建一个新的 store 实例
// store只针对数据，跳转不需要store进行
const store = createStore({
  state() {
    return {
      // 用户信息
      user: {},
    }
  },
  mutations: {
    SET_USERINFO(state, user) {
      state.user = user
    },
  },
  actions: {
    loginAction({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        loginApi(username, password)
          .then((res) => {
            if (res.data) {
              const token = res.data.token
              setToken(token)
              resolve(res)
            }
          })
          .catch((err) => reject(err))
      })
    },
    getinfoAction({ commit }) {
      return new Promise((resolve, reject) => {
        getInfoApi().then((res) => {
          commit('SET_USERINFO', res.data)
          resolve(res)
        })
      })
    },
    logoutAction({ commit }) {
      return new Promise((resolve, reject) => {
        logoutApi().then((res) => {
          removeToken()
          commit('SET_USERINFO', {})
          resolve()
        })
      })
    },
  },
})

export default store
